//
//  DAUMonHumitureTVC.m
//  DAU-iOS
//
//  Created by XiangDongMBP on 2016/11/18.
//  Copyright © 2016年 East. All rights reserved.
//

#import "DAUMonHumitureTVC.h"
#import "XDSelSecureLineView.h"
#import "DAUMonWarnItemTCell.h"

@interface DAUMonHumitureTVC ()<XDSelSecureLineViewDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak,   nonatomic) IBOutlet UIButton *headerTempLowerBtn;
@property (weak,   nonatomic) IBOutlet UIButton *headerTempUpperBtn;

@property (nonatomic, readonly) DAUCollectorInfoModel *model;

@end

static NSString *const kReuseCellId = @"DAUMonWarnItemTCell";

@implementation DAUMonHumitureTVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    [self initSubViews];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self refreshWholeView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (DAUCollectorInfoModel *)model {
    return DAU_APP_DELEGATE.dauModel.engineDetail.result;
}

- (void)initSubViews {
//    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kReuseCellId];
//    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
//    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    
    self.headerTempUpperBtn.layer.cornerRadius = 2;
    self.headerTempUpperBtn.layer.borderWidth = 1;
    self.headerTempUpperBtn.layer.borderColor = DAU_COLOR_SeparotorLine(1.0).CGColor;
    self.headerTempLowerBtn.layer.cornerRadius = 2;
    self.headerTempLowerBtn.layer.borderWidth = 1;
    self.headerTempLowerBtn.layer.borderColor = DAU_COLOR_SeparotorLine(1.0).CGColor;
    
    [self.headerTempLowerBtn addTarget:self action:@selector(tempBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.headerTempUpperBtn addTarget:self action:@selector(tempBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView = self.headerBgView;
    
//    [self refreshWholeView];
}

- (void)refreshWholeView {
    [self.headerTempLowerBtn setTitle:[NSString stringWithFormat:@"%.0f ℃", self.model.tempLower / DAUModelContactValueBaseMul]
                             forState:UIControlStateNormal];
    [self.headerTempUpperBtn setTitle:[NSString stringWithFormat:@"%.0f ℃", self.model.tempUpper / DAUModelContactValueBaseMul]
                             forState:UIControlStateNormal];
    
    [self.tableView reloadData];
}

#pragma mark - <UITableViewDelegate>代理
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - <UITableViewDataSource>代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.temperature.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:kReuseCellId];
    }
//    DAUMonWarnItemTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
//    [cell configViewWithHumitureItem:item dAUCollectorInfoModel:self.model];
    
    DAUColContactItem *item = self.model.temperature[indexPath.row];
    cell.textLabel.font = [UIFont systemFontOfSize:14];
    cell.textLabel.text = item.name;
    
    cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:14];
    cell.detailTextLabel.text = (item.state == 0) ? NSLocalizedString(@"故障", nil) : [NSString stringWithFormat:@"%.1f ℃", item.value / DAUModelContactValueBaseMul];
    
//    UIColor *textColor;
    if ((item.state == 0) || (item.value < self.model.tempLower) || (item.value > self.model.tempUpper)) {
//        textColor = DAU_COLOR_NavBg(1.0);
        cell.detailTextLabel.textColor = DAU_COLOR_NavBg(1.0);
    } else {
//        textColor = DAU_COLOR_FontNor(1.0);
        cell.detailTextLabel.textColor = DAU_COLOR_FontNor(1.0);
    }
    cell.textLabel.textColor = DAU_COLOR_FontNor(1.0);
    
    return cell;
}

#pragma mark - <XDSelSecureLineViewDelegate>
- (void)xDSelSecureLineView:(XDSelSecureLineView *)selPhotoView lower:(NSInteger)lower upper:(NSInteger)upper {
    lower = lower * DAUModelContactValueBaseMul;
    upper = upper * DAUModelContactValueBaseMul;
    if ((lower != self.model.tempLower) || (upper != self.model.tempUpper)) {
        [self requestSetTemSecureLine:lower upper:upper];
    }
}

#pragma mark - 按键处理
- (void)tempBtnTapped:(UIButton *)btn {
    XDSelSecureLineView *view = [[XDSelSecureLineView alloc] initWithLower:self.model.tempLower / DAUModelContactValueBaseMul
                                                                     upper:self.model.tempUpper / DAUModelContactValueBaseMul
                                                                  delegate:self];
    [view showInView:self.view];
}

#pragma mark - 网络请求
- (void)requestSetTemSecureLine:(NSInteger)lower upper:(NSInteger)upper {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    NSDictionary *pars = @{@"id"  : @(DAU_APP_DELEGATE.dauModel.engineDetail.result.collectorId),
                           @"temperature_secure_line_lower" : @(lower),
                           @"temperature_secure_line_upper" : @(upper)};
    
    NSString *urlStr = [DAUUrlProtocolMerger apiSecureLine];
    [XDAFHttpRequest PUT:urlStr parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"设置干接点成功返回%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[@"errCode"] integerValue] == 200) {
            self.model.tempLower = lower;
            self.model.tempUpper = upper;
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[@"msg"]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"设置干接点失败%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:NSLocalizedString(@"网络请求失败", nil)];
    }];
}

@end
